#include "contacttablemodel.h"
#include "contactitem.h"
#include <QBrush>
#include <QTextBrowser>
#include <QAbstractTextDocumentLayout>
#include <QPainter>
#include <QStyleOptionViewItem>
#include <QApplication>
#include <contactitem.h>
#define IMAGE_COLUMN   0
#define INFO_COLUMN    1




ContactItemDelegate::ContactItemDelegate(QObject * parent)
    :QStyledItemDelegate(parent)
{
    browser = new QTextBrowser;
    browser->setLineWrapMode(QTextBrowser::NoWrap);
}

ContactItemDelegate::~ContactItemDelegate()
{
    delete browser;
}


void ContactItemDelegate::paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{

    switch(index.column())
    {
    case IMAGE_COLUMN:
        QStyledItemDelegate::paint(painter, option, index);
        break;

    case INFO_COLUMN:
        {
            painter->save();


            QString strValue;
            strValue = index.data().value<QString>();
            if ( (option.state&QStyle::State_Selected)&&
                (option.state&QStyle::State_Active) )
            {
                strValue.insert(0,"<font color = 'white'>");
                strValue.replace("color='gray'>", "color='lightgray'>");
            }
            else
            {
                strValue.insert(0,"<font color = 'black'>");
            }


            QRect rect = option.rect;

            if (option.state&QStyle::State_Selected)
            {
                QStyleOptionViewItemV4 style = option;
                initStyleOption(&style, index);
                style.text = "";
                style.widget->style()->drawControl(QStyle::CE_ItemViewItem, &style, painter);
            }
           else
            {
               QBrush brush(index.data(Qt::BackgroundRole).value<QBrush>());
               painter->fillRect(rect, brush);
            }

           painter->translate(rect.x(),rect.y());
            QAbstractTextDocumentLayout::PaintContext context;
            browser->setHtml(strValue);
            browser->document()->setPageSize( rect.size());
            browser->document()->documentLayout()->draw(painter, context);



            painter->restore();
        }
        break;
    default:
        break;

    }
}

ContactTableModel::ContactTableModel(QObject *parent)
     : QAbstractTableModel(parent)
 {
 }

 ContactTableModel::ContactTableModel(ContactList list, QObject *parent)
     : QAbstractTableModel(parent)
 {
     contacts=list;
 }

 void ContactTableModel::updateRow(ContactItem const& item)
 {
     int row = 0;
     if (!contacts.contains(item)) {
         insertRows(0, 1, QModelIndex());
         contacts.replace(row, item);
     }
     else
     {
         row = contacts.indexOf(item);

         ContactItem contact(contacts.at(row));
         contact.update(item);
         contacts.replace(row, contact);

     }

     QModelIndex from = index(row, 0, QModelIndex());
     QModelIndex to = index(row, 1, QModelIndex());
     dataChanged(from, to);
 }


 int ContactTableModel::rowCount(const QModelIndex &parent) const
  {
      Q_UNUSED(parent);
      return contacts.size();
  }

  int ContactTableModel::columnCount(const QModelIndex &parent) const
  {
      Q_UNUSED(parent);
      return 2;
  }

  QVariant ContactTableModel::data(const QModelIndex &index, int role) const
   {
       if (!index.isValid())
           return QVariant();

       if (index.row() >= contacts.size() || index.row() < 0)
           return QVariant();

       ContactItem item = contacts.at(index.row());
       switch (role)
       {
       case Qt::DisplayRole:
       {
           if (index.column() == 0)
               return QVariant();
           else if (index.column() == 1)
           {
               QString strDisplay;
               strDisplay = QString("%1</font><br><font size=2 color='gray'>%2</font>").arg(item.name().c_str()).arg(item.jid().c_str());
               return strDisplay;
           }
       }
           break;
       case Qt::DecorationRole:
               if (index.column() == 0)
               {
                   return item.scaledImage();
               }
           break;
       case Qt::BackgroundRole:
           return index.row()%2?QBrush(QColor(255,255,255)):QBrush(QColor(237,243,255));
           break;
       case Qt::SizeHintRole:
           if (index.column() == 0)
                return QSize(42,42);
           break;

       case KeyRole:
           return qVariantFromValue(item);
           break;

       }
       return QVariant();
   }

  QVariant ContactTableModel::headerData(int section, Qt::Orientation orientation, int role) const
  {
      switch ( role )
      {
      case Qt::DisplayRole:
          if (orientation == Qt::Horizontal) {
              switch (section) {
                  case 0:
                      return tr("");

                  case 1:
                      return tr("");

                  default:
                      return QVariant();
              }
          }
          break;
          case Qt::SizeHintRole:
          {
              switch (section) {
              case 0:
                  return QSize(42,0);

              case 1:
                  //return QSize(255, 20);
              default:
                  return  QVariant();
              }
          }


      }
       if (role != Qt::DisplayRole)
           return QVariant();

         return QVariant();
   }

  bool ContactTableModel::insertRows(int position, int rows, const QModelIndex &index)
   {
       Q_UNUSED(index);
       beginInsertRows(QModelIndex(), position, position+rows-1);

       for (int row=0; row < rows; row++) {
           ContactItem item;
           contacts.insert(position, item);
       }

       endInsertRows();
       return true;
   }

  bool ContactTableModel::removeRows(int position, int rows, const QModelIndex &index)
   {
       Q_UNUSED(index);
       beginRemoveRows(QModelIndex(), position, position+rows-1);

       for (int row=0; row < rows; ++row) {
           contacts.removeAt(position);
       }

       endRemoveRows();
       return true;
   }


  Qt::ItemFlags ContactTableModel::flags(const QModelIndex &index) const
   {
       if (!index.isValid())
           return Qt::ItemIsEnabled;

       return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
   }

